import React, { useState, useRef } from 'react'
import { Input, Space, Button } from 'antd'
import { addBanner } from './../../api/banner'
function BannerAdd(props) {
  const [ alt, setAlt ] = useState('')
  const [ link, setLink ] = useState('')


  const [ uri, setUri ] = useState('')
  const fileRef = useRef()
  const imgRef = useRef()

  const getFile = () => {
    console.log(fileRef.current) // 查看打印数据得知
    const file = fileRef.current.input.files[0]
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = function () {
      setUri(this.result)
    }
  }

  const getData = () => {
    const data = {
      alt,
      link,
      img: uri
    }
    console.log(data)
    addBanner(data).then(() => {
      // 跳转到列表页面
      console.log(props)
      props.history.push('/banner/list')
    })
  }
  return (
    <Space direction="vertical">
      <Input type="text" placeholder="alt" onChange = { e => {
        setAlt(e.target.value)
      }}></Input>
      <Input type="text" placeholder="link" onChange = { e => {
        setLink(e.target.value)
      }}></Input>
      <Input type="file" ref = { fileRef } onChange = { getFile }></Input>
      <img src={ uri } alt="" ref={ imgRef }/>
      <Button type="primary" onClick = { getData }>上传</Button>
    </Space>
  )
}

export default BannerAdd
